package org.web.clientlistmanager.client.biz;


import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.web.clientlistmanager.sdk.dto.ClmRequest;
import org.web.clientlistmanager.sdk.dto.ResultDTO;
import org.web.clientlistmanager.sdk.event.EventInterface;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.Map;

@Component("clmReportSelfAckEvent")
public class ClmReportSelfAckEvent implements EventInterface {

    private static final Logger logger = LogManager.getLogger(ClmNettyClientHandler.class);


    @Resource
    private ClmClientMonitor clientMonitor;

    /**
     *
     * */
    @Override
    public void executeRequest(ClmRequest clmRequest, ChannelHandlerContext ctx) {
        logger.info("Received report self ack event");
        ResultDTO resultDTO = null;
        try {
            resultDTO = fromMap((Map<String, Object>) clmRequest.getContent());
            if (resultDTO.isSuccess()) {
                clientMonitor.hasReportSelf = true;
                clientMonitor.setServerPartProcessByReportSelfAck(resultDTO.getResult());
            } else {
                logger.error("Report self ack event failed, message is " + resultDTO.getResult());
            }
        } catch (Exception e) {
            logger.error(e);
        }

    }

    private ResultDTO fromMap(Map<String, Object> map) throws Exception {
        ResultDTO resultDTO = new ResultDTO();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            Field field = ResultDTO.class.getDeclaredField(key);
            field.setAccessible(true);
            field.set(resultDTO, value);
        }
        return resultDTO;
    }
}
